# 日程管理路由
from flask import Blueprint, render_template, request, jsonify
from models import db
from models.schedule import Event, EventReminder
from datetime import datetime, date, timedelta

schedule_bp = Blueprint('schedule', __name__, url_prefix='/schedule')

@schedule_bp.route('/')
def calendar():
    """显示日程日历页面"""
    return render_template('schedule.html')

@schedule_bp.route('/api/events', methods=['GET'])
def get_events():
    """获取事件列表"""
    # 获取日期范围
    start_date_str = request.args.get('start')
    end_date_str = request.args.get('end')
    category = request.args.get('category')
    
    query = Event.query
    
    if start_date_str:
        try:
            start_date = datetime.fromisoformat(start_date_str.replace('Z', '+00:00'))
            query = query.filter(Event.start_time >= start_date)
        except:
            pass
    
    if end_date_str:
        try:
            end_date = datetime.fromisoformat(end_date_str.replace('Z', '+00:00'))
            query = query.filter(Event.start_time <= end_date)
        except:
            pass
    
    if category:
        query = query.filter_by(category=category)
    
    events = query.order_by(Event.start_time).all()
    
    return jsonify({
        'events': [event.to_dict() for event in events]
    })

@schedule_bp.route('/api/events', methods=['POST'])
def create_event():
    """创建新事件"""
    data = request.json
    
    # 解析时间
    try:
        start_time = datetime.fromisoformat(data['start_time'].replace('Z', '+00:00'))
    except:
        return jsonify({'error': '无效的开始时间'}), 400
    
    end_time = None
    if data.get('end_time'):
        try:
            end_time = datetime.fromisoformat(data['end_time'].replace('Z', '+00:00'))
        except:
            pass
    
    event = Event(
        title=data['title'],
        description=data.get('description', ''),
        start_time=start_time,
        end_time=end_time,
        location=data.get('location', ''),
        category=data.get('category', '其他'),
        color=data.get('color', '#4a90e2'),
        is_all_day=data.get('is_all_day', False),
        reminder_minutes=data.get('reminder_minutes', 15)
    )
    
    db.session.add(event)
    db.session.commit()
    
    return jsonify({
        'success': True,
        'event': event.to_dict()
    }), 201

@schedule_bp.route('/api/events/<int:event_id>', methods=['GET'])
def get_event(event_id):
    """获取事件详情"""
    event = Event.query.get_or_404(event_id)
    return jsonify(event.to_dict())

@schedule_bp.route('/api/events/<int:event_id>', methods=['PUT'])
def update_event(event_id):
    """更新事件"""
    event = Event.query.get_or_404(event_id)
    data = request.json
    
    if 'title' in data:
        event.title = data['title']
    if 'description' in data:
        event.description = data['description']
    if 'start_time' in data:
        try:
            event.start_time = datetime.fromisoformat(data['start_time'].replace('Z', '+00:00'))
        except:
            pass
    if 'end_time' in data:
        try:
            event.end_time = datetime.fromisoformat(data['end_time'].replace('Z', '+00:00'))
        except:
            pass
    if 'location' in data:
        event.location = data['location']
    if 'category' in data:
        event.category = data['category']
    if 'color' in data:
        event.color = data['color']
    if 'is_all_day' in data:
        event.is_all_day = data['is_all_day']
    if 'reminder_minutes' in data:
        event.reminder_minutes = data['reminder_minutes']
    
    db.session.commit()
    
    return jsonify({
        'success': True,
        'event': event.to_dict()
    })

@schedule_bp.route('/api/events/<int:event_id>', methods=['DELETE'])
def delete_event(event_id):
    """删除事件"""
    event = Event.query.get_or_404(event_id)
    db.session.delete(event)
    db.session.commit()
    
    return jsonify({
        'success': True,
        'message': '删除成功'
    })

@schedule_bp.route('/api/month-events', methods=['GET'])
def get_month_events():
    """获取指定月份的事件（按日期分组）"""
    year = request.args.get('year', type=int)
    month = request.args.get('month', type=int)
    
    if not year or not month:
        today = date.today()
        year = today.year
        month = today.month
    
    # 计算月份的起止日期
    start_date = date(year, month, 1)
    if month == 12:
        end_date = date(year + 1, 1, 1)
    else:
        end_date = date(year, month + 1, 1)
    
    # 查询事件
    events = Event.query.filter(
        Event.start_time >= start_date,
        Event.start_time < end_date
    ).order_by(Event.start_time).all()
    
    # 按日期分组
    events_by_date = {}
    for event in events:
        date_key = event.start_time.date().isoformat()
        if date_key not in events_by_date:
            events_by_date[date_key] = []
        events_by_date[date_key].append(event.to_dict())
    
    return jsonify({
        'events_by_date': events_by_date
    })

@schedule_bp.route('/api/today-events', methods=['GET'])
def get_today_events():
    """获取今日事件及本周统计"""
    # 修复：使用UTC时间
    now_utc = datetime.utcnow()
    today_start_utc = datetime(now_utc.year, now_utc.month, now_utc.day)
    tomorrow_start_utc = today_start_utc + timedelta(days=1)
    
    # 今日事件
    events = Event.query.filter(
        Event.start_time >= today_start_utc,
        Event.start_time < tomorrow_start_utc
    ).order_by(Event.start_time).all()
    
    # 本周事件统计（修复：使用UTC时间）
    today_date_utc = now_utc.date()
    week_start_date = today_date_utc - timedelta(days=today_date_utc.weekday())  # 周一
    week_start_utc = datetime(week_start_date.year, week_start_date.month, week_start_date.day)
    week_end_utc = week_start_utc + timedelta(days=7)  # 下周一
    
    week_events_count = Event.query.filter(
        Event.start_time >= week_start_utc,
        Event.start_time < week_end_utc
    ).count()
    
    return jsonify({
        'count': len(events),
        'week_count': week_events_count,  # 本周事件总数
        'events': [{
            'title': event.title,
            'start_time': event.start_time.strftime('%H:%M'),
            'location': event.location
        } for event in events]
    })

